#### Packages ####
sapply(c("lme4","texreg","ggplot2", "dplyr", "cowplot", "tidyr"),
       FUN = function(x){library(x, character.only = TRUE)})
#### Loading tables from the database ####
sapply(c("IACtHRcases.RData", "IACtHRmerits.RData",
         "IACtHRobjections.RData", "IACtHRamici.RData", 
         "IACtHRvictims.RData", "IACtHRremedies.RData", 
         "IACtHRopinions.RData","IACtHRdissents.RData", 
         "IACtHRcompliance.RData"), 
       FUN = function(x){load(x, .GlobalEnv)})

#### Various descriptives reported in the manuscript ####
length(unique(IACtHRremedies$MeasureType2))
length(unique(IACtHRmerits$CaseID))
length(unique(IACtHRcases$CaseID))
length(unique(IACtHRremedies$CaseID))
nrow(IACtHRobjections)
length(unique(IACtHRobjections$CaseID))
length(unique(IACtHRamici$CaseID))
table(IACtHRmerits$DecisionOutcome)
summary(ifelse(IACtHRmerits$AcknowledgedByState == "Yes" | IACtHRmerits$AcknowledgedByState == "Partly",1,0))

IACtHRremedies$MeasureType2 <- ifelse(IACtHRremedies$MeasureType2 == "Prosectution of perpetrator/investigation of crime",
                                      "Prosecution of perpetrator/\ninvestigation of crime",
                                      IACtHRremedies$MeasureType2)

pdf("RemediesFreq.pdf")
ggplot(IACtHRremedies[which(is.na(IACtHRremedies$MeasureType2) == FALSE),])+
  geom_bar(aes(x=reorder(MeasureType2, -table(MeasureType2)[MeasureType2])),
           stat = "count")+
  coord_flip()+
  theme(axis.text = element_text(size = 12),
        axis.title = element_text(size = 12),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  xlab("Type of remedy")+
  ylab("N")
dev.off()


table(IACtHRopinions$OpinionType)
table(IACtHRopinions$OpinionSubject)


opinionplot <- ggplot(IACtHRopinions)+
  geom_bar(aes(x = reorder(OpinionSubject, -table(OpinionSubject)[OpinionSubject]),
               fill = OpinionType))+
  theme_classic()+
  xlab("Type of decision")+
  ylab("N")+
  coord_flip()+
  ggtitle("Separate, concurring and dissenting opinions")+
  ylim(0,400)+
  scale_fill_grey(name = "Opinion type")



IACtHRdissents$DissentDirection <- ifelse(IACtHRdissents$DissentDirection == "Voted pro government",
                                          "Pro-\ngovernment",
                                          ifelse(IACtHRdissents$DissentDirection == "Voted anti government",
                                                 "Anti-\ngovernment",
                                                 "Unclear"))
dissentplot <- ggplot(IACtHRdissents)+
  geom_bar(aes(x = reorder(TypeVote, -table(TypeVote)[TypeVote]),
               fill = DissentDirection))+
  theme_classic()+
  coord_flip()+
  xlab("Type of decision")+
  ylab("N")+
  ggtitle("Dissenting votes")+
  ylim(0,400)+
  scale_fill_grey(name = "Direction of\ndissent")

pdf("JudicialBehavior.pdf")
ggdraw()+
  draw_plot(opinionplot, x = 0, y = 0.5, width = 1, height = 0.5)+
  draw_plot(dissentplot, x = 0, y = 0, width = 1, height = 0.5)
dev.off()

IACtHRobjections$PreliminaryObjectionReason
IACtHRobjections <- IACtHRobjections %>% 
  mutate(objectionReasons2 = ifelse(grepl("domestic remedies", PreliminaryObjectionReason),"Failure to exhaust domestic remedies", "Other"),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "the victim did not bring forth any type of action before the domestic tribunals the impediment of his departure in January 2003","Failure to exhaust domestic remedies",objectionReasons2),
         objectionReasons2 = ifelse(grepl("jurisdiction", PreliminaryObjectionReason), "Lack of jurisdiction/competence", objectionReasons2),
         objectionReasons2 = ifelse(grepl("competence", PreliminaryObjectionReason), "Lack of jurisdiction/competence", objectionReasons2),
         objectionReasons2 = ifelse(grepl("Commission", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(grepl("competency", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(grepl("competent", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "Failure to promote friendly settlement", "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason =="Failure to carry out on-site investigation", "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(grepl("article 51", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(grepl("article 50", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(grepl("Articles 50", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(grepl("articles 50", PreliminaryObjectionReason), "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "Challenged objectivity of the court"|
                                      PreliminaryObjectionReason == "the prejudice of Judges Cecilia Medina Quiroga and Diego García-Sayan"|
                                      PreliminaryObjectionReason == "certain judges on the Court are biased" | 
                                      PreliminaryObjectionReason == "Partiality of some judges", "Bias of Court or its judges", objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "expiration of the time limit for filing the petition to the Court" |
                                      PreliminaryObjectionReason == "Application not within stipulated time-frame" |
                                      grepl("six-month", PreliminaryObjectionReason), "Application filed too late", objectionReasons2), 
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "failure to attempt a friendly settlement", "Challenges actions of commission", objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "Domestic remedies available", "Failure to exhaust domestic remedies", objectionReasons2),
         objectionReasons2 = ifelse(grepl("due process", tolower(PreliminaryObjectionReason)), "Due process violated for the state",objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "violates right to defense for state", "Due process violated for the state",objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "Breach of fourth instance rule", "Breach of fourth instance rule",  objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "Contests facts", "Contests facts", objectionReasons2),
         objectionReasons2 = ifelse(PreliminaryObjectionReason == "Court will act as a trial court for individual facts", "Breach of fourth instance rule", objectionReasons2),
         objectionReasons2 = ifelse(grepl("representative", tolower(PreliminaryObjectionReason)), "Actions of victims' representatives",objectionReasons2 ))



IACtHRobjections %>% 
  group_by(CaseID) %>% 
  summarize(jurisdiction = ifelse(sum(objectionReasons2 == "Lack of jurisdiction/competence")>0,1,0),
            commission = ifelse(sum(objectionReasons2 == "Challenges actions of commission")>0,1,0),
            domesticRemedies = ifelse(sum(objectionReasons2 == "Failure to exhaust domestic remedies")>0,1,0),
            other = ifelse(sum(objectionReasons2 != "Lack of jurisdiction/competence" &
                                 objectionReasons2 != "Challenges actions of commission" &
                                 objectionReasons2 != "Failure to exhaust domestic remedies")>0,1,0)) %>% 
  right_join(select(IACtHRcases, CaseID, DateMeritsRuling)) %>% 
  mutate(anyObjection = ifelse(is.na(jurisdiction),0,1),
         jurisdiction = ifelse(is.na(jurisdiction),0,jurisdiction),
         commission = ifelse(is.na(commission),0, commission),
         domesticRemedies = ifelse(is.na(domesticRemedies), 0, domesticRemedies), 
         other = ifelse(is.na(other), 0, other)) %>% 
  mutate(year = as.integer(substr(DateMeritsRuling,1,4)),
         Decade = factor(ifelse(year < 2000, "1980s & 1990s", 
                                ifelse(year < 2010, "2000s", "2010s")),
                         levels = c(  "2010s","2000s", "1980s & 1990s"))) %>% 
  group_by(Decade) %>%
  summarize(jurisdiction  = mean(jurisdiction),
            commission = mean(commission),
            domesticRemedies = mean(domesticRemedies),
            other = mean(other),
            anyObjection = mean(anyObjection)) %>% 
  gather(-Decade, key = "Objection", value = "share") %>% 
  mutate(Objection = ifelse(Objection == "other", "Other objections", Objection), 
         Objection = ifelse(Objection =="jurisdiction", "Against the jurisdiction\nof the Court", Objection),
         Objection = ifelse(Objection == "commission", "Against activities\nof the Commission", Objection), 
         Objection = ifelse(Objection == "domesticRemedies", "Domestic remedies\nnot exhausted", Objection),
         Objection = ifelse(Objection == "anyObjection", "Any preliminary\nobjection", Objection),
         Objection = factor(Objection, levels = c("Any preliminary\nobjection",
                                                  "Other objections",
                                                  "Against activities\nof the Commission",
                                                  "Against the jurisdiction\nof the Court",
                                                  "Domestic remedies\nnot exhausted"))) %>% 
  ggplot(aes(x = Objection,
             y = share, fill = Decade)) +
  geom_bar(stat = "identity", position="dodge") +
  coord_flip()+
  scale_fill_grey(name = "Period")+
  xlab("") +
  ylab("Share of cases") +
  theme_classic()
ggsave("PreliminaryObjectionFigure.pdf", height = 7, width = 7)




mean(IACtHRobjections$objectionReasons2 == "Failure to exhaust domestic remedies" |
       IACtHRobjections$objectionReasons2 == "Lack of jurisdiction/competence" |
       IACtHRobjections$objectionReasons2 == "Challenges actions of commission")                              
         

IACtHRobjections$PreliminaryObjectionCount <-1
IACtHRobjections$PreliminaryObjectionCount <- ave(IACtHRobjections$PreliminaryObjectionCount,
                                                  IACtHRobjections$CaseID,
                                                  FUN = sum) 

IACtHRcases$CaseID[(IACtHRcases$CaseID %in% unique(IACtHRmerits$CaseID)) == FALSE]

dt <- merge(IACtHRmerits,
            IACtHRobjections[which(duplicated(IACtHRobjections$CaseID) == FALSE),],
            by = "CaseID",
            all.x = TRUE)

dt$PreliminaryObjectionCount <- ifelse(is.na(dt$PreliminaryObjectionCount), 0, dt$PreliminaryObjectionCount)


dt <- merge(dt,
            IACtHRcases,
            by = "CaseID",
            all.x = TRUE)
length(unique(dt$CaseID))

IACtHRamici$amiciCount <- 1
IACtHRamici$amiciCount <- ave(IACtHRamici$amiciCount,
                              IACtHRamici$CaseID,
                              FUN = sum)

dt <- merge(dt,
            IACtHRamici[which(duplicated(IACtHRamici$CaseID) == FALSE),],
            by = "CaseID",
            all.x = TRUE)

dt$amiciCount <- ifelse(is.na(dt$amiciCount),0, dt$amiciCount)
names(dt)
dt$InrelationToArticle2 <- ifelse(dt$InRelationTo == "Article 2. Domestic Legal Effects",1,0)


table(dt$AcceptInternationalResponsibility)

dt$AcknowledgedByState1 <- ifelse(is.na(dt$AcknowledgedByState),0,
                                  ifelse(dt$AcknowledgedByState == "Yes" |dt$AcknowledgedByState == "Partly" ,1,
                                         0))

dt$AcknowledgedByState2 <- ifelse(is.na(dt$AcknowledgedByState),0,
                                  ifelse(dt$AcknowledgedByState == "Yes" ,1,
                                         0))

IACtHRvictims$CaseID <- NULL
dt <- merge(dt,
            IACtHRvictims,
            by = "VictimID",
            all.x = TRUE)


dt$adhocJudge <- ifelse(dt$AdhocJudgesInMeritsHearing == "Not Relevant",0,1)

mod1 <- glmer(ifelse(DecisionOutcome == "Violation",1,0) ~
                sqrt(PreliminaryObjectionCount)+
                ifelse(AllegedBy == "Representatives of Applicants",1,0) +
                InrelationToArticle2 +
                amiciCount +
                CollectiveVictim +
                (1 |  RespondentState / CaseID),
              family = binomial(link = "logit"),
              control = glmerControl(optimizer = "bobyqa", optCtrl=list(maxfun=20000)),
              data = dt)

summary(mod1)

mod2 <- glmer(ifelse(DecisionOutcome == "Violation",1,0) ~
                ifelse(PreliminaryObjectionCount > 0,1,0)+
               ifelse(AllegedBy == "Representatives of Applicants",1,0) +
                InrelationToArticle2 +
                amiciCount +
                CollectiveVictim +
                (1 |  RespondentState / CaseID),
              family = binomial(link = "logit"),
             control = glmerControl(optimizer = "bobyqa", optCtrl=list(maxfun=20000), nAGQ = 15),
              data = dt)
summary(mod2)
mod3 <- glmer(ifelse(DecisionOutcome == "Violation",1,0) ~
                AcknowledgedByState1+
                ifelse(AllegedBy == "Representatives of Applicants",1,0) +
                InrelationToArticle2 +
                amiciCount +
                CollectiveVictim +
                #HRprotectionLatentmean +
                #(1 | IACHRarticle)+
                (1 |  RespondentState / CaseID),
              family = binomial(link = "logit"),
              control = glmerControl(optimizer = "bobyqa", optCtrl=list(maxfun=20000)),
              data = dt)
summary(mod3)


mod4 <- glmer(ifelse(DecisionOutcome == "Violation",1,0) ~
                AcknowledgedByState2+
                ifelse(AllegedBy == "Representatives of Applicants",1,0) +
                InrelationToArticle2 +
                amiciCount +
                CollectiveVictim +
                (1 |  RespondentState / CaseID),
              family = binomial(link = "logit"),
                control = glmerControl(optimizer = "bobyqa", optCtrl=list(maxfun=20000)),
              data = dt)

summary(mod4)
table(dt$RespondentState)

table(IACtHRmerits$AcknowledgedByState, IACtHRmerits$DecisionOutcome)

texreg(list(mod1, mod2, mod3, mod4),
       stars = c(0.001, 0.01, 0.05, 0.1),
       symbol = "\\dagger",
       caption = "The Decision-Making of the IACtHR: Multilevel logistic regressions",
       fontsize = "tiny",
       caption.above = TRUE,
       label = "tab:analysis",
       custom.coef.map = list("sqrt(PreliminaryObjectionCount)" = "$\\sqrt{\\textrm{Number of preliminary objections}}$",
                              "ifelse(PreliminaryObjectionCount > 0, 1, 0)" = "At least one preliminary objection",
                              "AcknowledgedByState1" = "State acknowledged partial or full responsibility",
                              "AcknowledgedByState2" = "State acknowledged full responsibility",
                              'ifelse(AllegedBy == "Representatives of Applicants", 1, 0)' = "Only alleged by victim's representatives",
                              "InrelationToArticle2" ="In relation to obligation to give domestic effect",
                              "amiciCount" = "Number of \\emph{amici} briefs",
                              "CollectiveVictimYes" = "Collective victim",
                              "(Intercept)" = "Intercept"),
       file = "C:/Users/oyvinsti/Dropbox/IACtHRdata/IACtHRDataNote/exampleAnalysis.tex",
       custom.gof.names = c("AIC", "BIC", "Log Likelihood", "Number of decisions", "Number of cases",
                            "Number of respondent states",
                            "Variance of case intercept",
                            "Variance of respondent state intercept"))



